package com.demo.gateway.config;

import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import reactor.core.publisher.Mono;

import java.util.Objects;

/**
 * 限流配置
 *
 * @author DayDayUp
 * create on 2023-07-14
 **/
@Configuration
public class RateLimiterConfig {

    @Bean
    @Primary
    public KeyResolver ipKeyResolver() {
        return exchange -> {
            String hostString = Objects.requireNonNull(exchange.getRequest().getRemoteAddress()).getHostString();
            return Mono.just(hostString);
        };
    }

    @Bean
    public KeyResolver apiKeyResolver() {
        return exchange -> {
            String path = Objects.requireNonNull(exchange.getRequest().getPath().value());
            return Mono.just(path);
        };
    }
}
